<template>
    <div id="add-edit-mgr-user">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="769px" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="auto" :rules="rules">
                <el-row :gutter="35">
                    <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="ruleForm.name" placeholder="请输入姓名" clearable />
                        </el-form-item>
                    </el-col> -->
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('gongHao')" prop="jobNum">
                            <el-select 
                                v-model="ruleForm.jobNum" 
                                filterable class="m-2" 
                                :placeholder="$t('key_46')" 
                                size="large"
                                @change="jobNumChange"
                                value-key="id"
                            >
                                <el-option
                                    v-for="item in jobNumOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.jobNum"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_47')" prop="orgName">
                            <el-tree-select 
                                disabled
                                v-model="ruleForm.orgName" 
                                :data="menuInfo" 
                                :default-expand-all="true" 
                                :props="defaultProps"
                                :highlight-current="true"
                                :expand-on-click-node="false"
                                node-key="id"
                                :check-strictly="true"
                                @nodeClick="nodeClick"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_48')" prop="account">
                            <el-input v-model="ruleForm.account" :placeholder="$t('key_49')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="titleCon === '新增用户'" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_50')" prop="password">
                            <el-input v-model="ruleForm.password" show-password type="password" autocomplete="off" :placeholder="$t('key_51')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="titleCon === '新增用户'" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('key_52')" prop="confirm">
                            <el-input v-model="ruleForm.confirm" show-password type="password" autocomplete="off" :placeholder="$t('key_53')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="isShow" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('lC0zYgyhQ7oLepoCVfQy')" prop="grantRoleIdList">
                            <el-select 
                                v-model="ruleForm.grantRoleIdList"
                                filterable 
                                class="m-2" 
                                multiple
                                collapse-tags
                                :placeholder="$t('0Du71GgdXMmNXlOgIoRc')" 
                                size="large"
                                @change="useChange"
                                value-key="id"
                            >
                                <el-option
                                    v-for="item in useList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">{{ $t('key_24') }}</el-button>
                <el-button type="primary" :disabled="repeatDis" @click="submitForm(ruleFormRef)">{{ $t('key_25') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, computed , ref , reactive , toRefs , watch , toRef , toRaw , onMounted, Ref } from 'vue'
import { sysUserAdd , sysUserEdit , sysEmpSelector , getRolePage } from '/@/api/manage/manage.ts'
import { FormInstance, FormRules } from 'element-plus'
/*** 定义接口基础数据类型 */
interface formType {
    [propName:string] : any,
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
type ruleFormType = {
    [propName: string]: any,
    id: Number | String, // id
    // 账号(必填)
    account ?: String,
    // 部门(必填,用于显示)
    orgName ?: String,
    // 部门(必填,传给接口)
    orgId ?: String,
    // 姓名(必填)
    // name ?: String,
    // 密码(必填)
    password ?: String | Number,
    // 重复密码(必填)
    confirm ?: String | Number,
    // 工号
    jobNum ?: String,
    // 角色选择
    grantRoleIdList: [],
}
export default defineComponent( {
    name: 'add-edit-mgr-user',
    components: {},
    props:{
        menuInfo: {
            type: Array,
            default: []
        },
        isUseDialog: {
            type: Boolean,
            default: false
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref()
        const useList = ref()
        let setName:any = ''
        let setId:any = ''
        const isShow = ref(false)
        /*** filterTime 处理时间日期的该处暂未使用（不删除可能其他地方使用） */
        const filterTime = (time:string , timeType: string ) => {
            const date = new Date(time)
            const y = date.getFullYear()
            const m = date.getMonth() + 1 < 10 ? '0' + date.getMonth() : date.getMonth()
            const d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
            const h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
            const minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
            const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
            return timeType === 'yyyy-MM-dd' ? y + "-" + m + "-" + d : y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + s;
        }
        const defaultProps: object = {
            children: 'children',
            label: 'title',
        }
        const jobNumOptions = ref()

        /*** 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** GetWorkNum 获取员工工号 */
        const GetWorkNum = async () => {
            try {
                let res: { data: any[] } = await sysEmpSelector()
				console.log(res.data,'data')
                jobNumOptions.value = res.data
            } catch (err) {}

            let param = {
                pageNo: 1,
                pageSize: 999999,
            }
            try {
                let res: { data: any } = await getRolePage(param)
                useList.value = res.data.rows
                console.log(res.data.rows,'res数据')
            } catch (err) {}
        }

        /*** jobNumChange 工号下拉改变事件 */
        const jobNumChange = (val:any) => {
            let setArr = jobNumOptions.value.filter((i:any) => {
                return val === i.jobNum
            })
            console.log(setArr,'setArr')
            if(setArr.length !== 0){
                setArr.map((i:any) => {
                    setName = toRaw(i).orgName
                    setId = toRaw(i).id
                    state.ruleForm.orgName = toRaw(i).orgName
                    state.ruleForm.orgId = toRaw(i).orgId
                })
            }
        }

        /*** useChange 选择角色 */
        const useChange = (val:any) => {
            console.log(val,'val数据')
        }

        /*** watch 监听属性 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                state.repeatDis = false
                GetWorkNum()
                if(props.repairInfo !== ''){
                    isShow.value = false
                    titleCon.value = window.$t('key_54')
                    setId = JSON.parse(props.repairInfo).sysEmpInfo.id
                    state.ruleForm = JSON.parse(props.repairInfo)
                    state.ruleForm.jobNum = JSON.parse(props.repairInfo).sysEmpInfo.jobNum
                    state.ruleForm.orgName = JSON.parse(props.repairInfo).sysEmpInfo.orgName
                    state.ruleForm.orgId = JSON.parse(props.repairInfo).sysEmpInfo.orgId
                    state.ruleForm.SysEmpParam = JSON.parse(props.repairInfo).sysEmpInfo
                    console.log(JSON.parse(props.repairInfo),'repairInfo')
                }else{
                    // 初始化数据
                    titleCon.value = window.$t('key_55')
                    isShow.value = true
                    state.ruleForm = {
                        id: '',
                        // 账号
                        account: '',
                        // 部门(必填,用于显示)
                        orgName: '',
                        // 部门(必填,传给接口)
                        orgId : '',
                        // 姓名(必填)
                        // name: '',
                        // 密码(必填)
                        password:'',
                        // 重复密码(必填)
                        confirm: '',
                        // 工号
                        jobNum: '',
                        // 角色
                        grantRoleIdList: [],
                    }
                }
            }
        })

        /*** handleClose 关闭按钮 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /** cancelUseClick 取消按钮 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** validatorPass 密码表单验证 */
        const validatorPass = (rule: any, value: any, callback: any) => {
            if(value === ''){
                callback(new Error(window.$t('key_56'))) 
            }else{
                let str = value.replace(/\s*/g,'')
                state.ruleForm.password = str
                if(str.length < 6){
                    callback(new Error(window.$t('key_57'))) 
                    state.ruleForm.password = ''
                }else{
                    callback()
                }
            }
        }
        
        const nodeClick = (data: any) => {
            setName = toRaw(data).title
            state.ruleForm.orgId = toRaw(data).value
        }

        /*** validatorConfirm 确认密码验证 */
        const validatorConfirm = (rule: any, value: any, callback: any) => {
            if(value === ''){
                callback(new Error(window.$t('key_58'))) 
            }else{
                let str = value.replace(/\s*/g,'')
                state.ruleForm.confirm = str
                if(str.length < 6){
                    callback(new Error(window.$t('key_59'))) 
                    state.ruleForm.confirm = ''
                }else{
                    if(str !== state.ruleForm.password){
                        callback(new Error(window.$t('key_60')))
                        state.ruleForm.confirm = ''
                    }else{
                        callback()
                    }
                }
            }
        }

        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            password: [
				{ validator:validatorPass , required: true, trigger: 'blur' },
			],
            confirm: [
				{ validator:validatorConfirm , required: true, trigger: 'blur' },
			],
            // name: [
			// 	{ required: true, message: '请输入姓名', trigger: 'blur' },
			// ],
            orgName: [
				{ required: true, message: window.$t('key_31'), trigger: 'change' },
			],
            jobNum: [
				{required: true , message: window.$t('gongHaoBuNengWeiKong'), trigger: 'change' },
			],
            grantRoleIdList: [
				{required: true , message:window.$t('lvpoIgpwvm1MpT8LoMg2O'), trigger: 'change' },
			],
        })

        const ruleFormRef = ref()
        /** controlUseClick 确定按钮 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => {
                if (valid) {
                    let setObj = toRaw(state.ruleForm)
                    if(setObj.id === ''){
                        setObj.SysEmpParam = {
                            id: setId,
                            jobNum: toRaw(state.ruleForm).jobNum,
                            orgId: toRaw(state.ruleForm).orgId,
                            orgName: setName,
                        }
                        const {id , orgName , orgId , jobNum , ...param} = setObj
                        console.log(param,'param')
                        let res = await sysUserAdd(param)
                        if(res.success){
                            state.repeatDis = true
                            ctx.emit('controlUseClick')
                            ctx.emit('updateData')
                        }else{
                            ctx.emit('controlUseClick')
                        }
                    }else{
                        setObj.SysEmpParam.id = setId
                        setObj.SysEmpParam.jobNum = toRaw(state.ruleForm).jobNum
                        setObj.SysEmpParam.orgId = toRaw(state.ruleForm).orgId
                        setObj.SysEmpParam.orgName = toRaw(state.ruleForm).orgName
                        const {status , orgName , orgId , jobNum , ...param} = setObj
                        console.log(param,'param')
                        let res = await sysUserEdit(param)
                        if(res.success){
                            state.repeatDis = true
                            ctx.emit('controlUseClick')
                            ctx.emit('updateData')
                        }else{
                            ctx.emit('controlUseClick')
                        }
                    }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }
        return {
            cancelUseClick,
            submitForm,
            controlClick: false, // 防止重复提交（false为可以点击，true为禁止点击）
            isUseDialog, // 关闭弹窗的时候需要单独将其导出，注意：放在reactive中无效
            ...toRefs(state),
            titleCon,
            handleClose,
            ruleFormRef,
            rules,
            clean,
            defaultProps,
            nodeClick,
            jobNumOptions,
            jobNumChange,
            useList,
            useChange,
            isShow,
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-input){
        width: 100%;
    }
    :deep(.el-select){
        width: 100%;
    }
    .m-2{
        :deep(.el-input__inner){
            height: 32px!important;
        }
    }
</style>